/*
 * ResourceAnalyzer.cpp
 *
 *  Created on: Nov 4, 2008
 *      Author: Ryan
 */

#include "ResourceAnalyzer.h"

#include "../../OOInterface/Objects/Logger.h"



ResourceAnalyzer::ResourceAnalyzer()
{
}

ResourceAnalyzer::~ResourceAnalyzer()
{
}

const OOInterface::Point3f ResourceAnalyzer::findIdealLocation( const OOInterface::GameMap& map, const OOInterface::Resource& r, float radius ) const
{
	const float* mapResourceValues = computeMapResourceValues( map, r, radius );

	OOInterface::Point3f idealLoc = findMaxLocation( mapResourceValues, map.getWidth(), map.getHeight() );

	delete mapResourceValues;

	//OOInterface::Logger::getInstance("AI.txt") << "Resource Analyzer: " << idealLoc << std::endl;

	return idealLoc;
}

OOInterface::Point3f ResourceAnalyzer::findMaxLocation( const float* resources, unsigned int width, unsigned int height ) const
{
	OOInterface::Point3f p;
	float amt = 0.0f;

	for( unsigned int x = 0; x < width; ++x )
		for( unsigned int y = 0; y < height; ++y )
		{
			if( amt < resources[ convertToIndex(x,y, width)] )
			{
				amt = resources[ convertToIndex(x,y, width)];
				p.setX( x );
				p.setZ( y );
			}
		}

	return p;
}

const float* ResourceAnalyzer::computeMapResourceValues( const OOInterface::GameMap& map, const OOInterface::Resource& r, float radius ) const
{
	float* mapResourceValues = new float[ map.getWidth() * map.getHeight() ];

	for( unsigned int x = 0; x < map.getWidth(); ++x )
		for( unsigned int y = 0; y < map.getHeight(); ++y )
		{
			mapResourceValues[ convertToIndex(x,y, map.getWidth())] = resourceAmountAt( map, r, x, y, radius );
		}

	return mapResourceValues;
}

float ResourceAnalyzer::resourceAmountAt( const OOInterface::GameMap& map, const OOInterface::Resource& r, int locX, int locY, float radius ) const
{
	float amount = 0.0f;

	OOInterface::Point3f loc(locX, 0.0f, locY);

	int startX = (unsigned int) (-1 * radius + locX);
	if( startX < 0 ) startX = 0;

	int startY = (unsigned int) (-1 * radius + locY);
	if( startY < 0 ) startY = 0;

	OOInterface::Point3f point;

	unsigned int maxX = int(radius + locX);
	unsigned int maxY = int(radius + locY);

	for( unsigned int x = startX; x <= maxX && x < map.getWidth(); ++x )
	{
		for( unsigned int y = startY; y <= maxY && y < map.getHeight(); ++y )
		{
			point.setX(x); point.setZ(y);

			if( loc.distanceTo(point) < radius )
				amount += map.getResourceDensity( r, x, y );
		}
	}
	return amount;
}
